package models

import (
	//"fmt"
	"time"

	"github.com/jinzhu/gorm"
)

type PlanStatistics struct {
	gorm.Model
	Date            string         `gorm:"column:date"`
	PlansTotal       uint16         `gorm:"column:planstotal"`
	PlansPass           uint16         `gorm:"column:planspass"`
	PlansFail         uint16         `gorm:"column:plansfail"`	
	ExectTimes       int64          `gorm:"column:exectimes"` 
}

func (PlanStatistics) TableName() string {
	return "plan_statistics"
}

func (*PlanStatistics) Create(timeStr string) {
	record := PlanStatistics{}	
	record.Date = timeStr
	db.Create(&record)
}

func (*PlanStatistics) Get(date string) PlanStatistics{
	record := PlanStatistics{}
	db.Where("date=?",date).First(&record)	
	//fmt.Printf("plan:%+v", plan)
	return record

}

func (*PlanStatistics) GetList() []PlanStatistics {
	var records []PlanStatistics
	db.Order("created_at ASC").Limit(20).Find(&records)
	//fmt.Printf("plan:%+v", plan)
	return records
}

func (*PlanStatistics) AddTotalCount(date string) PlanStatistics{
	record := PlanStatistics{}
	db.Where("date=?",date).First(&record)
	count := record.PlansTotal
	count ++
	db.Model(&record).Where("date=?",date).Update("PlansTotal", count)	
	//fmt.Printf("plan:%+v", plan)
	return record

}


func (*PlanStatistics) AddPassCount(date string) PlanStatistics{
	record := PlanStatistics{}
	db.Where("date=?",date).First(&record)
	count := record.PlansPass
	count ++
	db.Model(&record).Where("date=?",date).Update("PlansPass", count)	
	//fmt.Printf("plan:%+v", plan)
	return record

}

func (*PlanStatistics) AddFailCount(date string) PlanStatistics{
	record := PlanStatistics{}
	db.Where("date=?",date).First(&record)
	count := record.PlansFail
	count ++
	db.Model(&record).Where("date=?",date).Update("PlansFail", count)	
	//fmt.Printf("plan:%+v", plan)
	return record

}

func (*PlanStatistics) AddExectTime(date string, cost float64) {
	record := PlanStatistics{}
	db.Where("date=?",date).First(&record)
	cost_t  := time.Duration(cost * 1000000000)	
	exectimes_t := time.Duration(record.ExectTimes * 1000000000)
	exectimes_t = exectimes_t + cost_t
	exectimes := int64(exectimes_t / 1000000000)
	db.Model(&record).Where("date=?",date).Update("ExectTimes", exectimes)	


}